<?php
/*
	本插件：$this->model('model')->方法名();
	其他地方调用：model('jy_seckill/model')->方法名();
*/
namespace jy_seckill;
defined('BY_JYA') or exit('error');
class model extends \plugin{
	public function redis($isnoexi=false){
			global $_RQ;
			static $redis;
			if (is_null($redis)) {
				$setting=config('setting');
				$config = $setting['redis'];
				if (!extension_loaded('redis')) {
					if($isnoexi){
						return error('PHP 未安装 redis 扩展');
					}else{
						exi('PHP 未安装 redis 扩展','error');
					}
				}
				if (!isset($setting['redis'])) {
					if($isnoexi){
						return error('未配置 redis, 请检查 data/config.php 中参数设置');
					}else{
						exi('未配置 redis, 请检查 data/config.php 中参数设置','error');
					}
				}
				if (empty($config['server'])) {
					$config['server'] = '127.0.0.1';
				}                                                                                             
				if (empty($config['port'])) {
					$config['port'] = '6379';
				}
				$redis_temp = new \Redis();
				if ($config['pconnect']) {
					$connect = $redis_temp->pconnect($config['server'], $config['port'], $config['timeout']);
				}else {
					$connect = $redis_temp->connect($config['server'], $config['port'], $config['timeout']);
				}
				if (!$connect) {
					if($isnoexi){
						return error('redis 连接失败, 请检查 data/config.php 中参数设置');
					}else{
						exi('redis 连接失败, 请检查 data/config.php 中参数设置','error');
					}
				}
				if (!empty($config['requirepass'])) {
					$redis_temp->auth($config['requirepass']);
				}
				try {
					$ping = $redis_temp->ping();
				}
				catch (ErrorException $e) {
					if($isnoexi){
						return error('redis 无法正常工作');
					}else{
						exi('redis 无法正常工作，请检查 redis 服务','error');
					}
				}

				if ($ping != '+PONG') {
					if($isnoexi){
						return error('redis 无法正常工作');
					}else{
						exi('redis 无法正常工作，请检查 redis 服务','error');
					}
				}
				$redis = $redis_temp;
			}else {
				try {
					$ping = $redis->ping();
				}
				catch (ErrorException $e) {
					$redis = NULL;
					$redis = redis();
					$ping = $redis->ping();
				}

				if ($ping != '+PONG') {
					$redis = NULL;
					$redis = redis();
				}
			}
			return $redis;
	}
	public function get_goods($taskid,$roomid,$timeid,$getnow=false){
		if (empty($taskid)) {
			$taskid = $this->getTodaySeckill();
			if (empty($taskid)) {
				//exi('今日没有秒杀，看看别的商品吧~','error','jy_weishop/index/');	
			}
		}
		$task =  $this->getTaskInfo($taskid);
		if (empty($task)) {
				//exi('未找到秒杀任务','error');
		}
		$rooms =  $this->getRooms($taskid);
		if (empty($rooms)) {
				//exi('未找到秒杀会场','error');
		}
		$room = false;
		$roomindex = 0;
		if (empty($roomid)) {
				foreach ($rooms as $row) {
					$room = $row;
					break;
				}
		}else {
				foreach ($rooms as $index => $row) {
					if ($row['id'] == $roomid) {
						$room = $row;
						$roomindex = $index;
						break;
					}
				}
		}
		if (empty($room)) {
				//exi('未找到秒杀会场','error');
		}
		$roomid = $room['id'];
		if(!$timeid){
			//获取专题时间点
			$alltimes =  $this->getTaskTimes($taskid);
			$currenttime = time();
			$times = array();
			$validtimes = array();
			paixu($alltimes,'time','asc');
			foreach($alltimes as $key => $tv) {
				$time['time']=$tv['time'];
				if (strlen($time['time']) == 1) {
					$timestr = '0' . $time['time'];
				}else{
					$timestr=$time['time'];
				}
				$starttime = strtotime(date('Y-m-d ' . $timestr . ':00:00'));
				$timegoods =  $this->model('model')->getSeckillGoods($taskid, $time['time'], 'all');
				$hasGoods = false;
				if($timegoods){
					foreach ($timegoods as $tg) {
						//if ($tg['timeid'] == $roomid) {
							$hasGoods = true;
							break;
						//}
					}
				}
				if (isset($alltimes[$key + 1])) {
					$end = $alltimes[$key + 1]['time'] - 1;
					$endtime = strtotime(date('Y-m-d ' . $end . ':59:59'));
				}else{
					$endtime = strtotime(date('Y-m-d 23:59:59'));
				}
				$setting=$this->plugin_setting('basic');
				if($setting['maxhours']>=1){
					$settime=$setting['maxhours']*3600+$starttime;
					$endtime=$settime<$endtime?$settime:$endtime;
				}
				if (($starttime <= $currenttime) && ($currenttime <= $endtime)) {
					$timeid = $time['time'];
				}else if ($currenttime < $starttime) {
					if (empty($timeid)) {
						$timeid = $time['time'];
					}
				}else {
					if ($endtime < $currenttime) {
						if (empty($timeid)) {
							$timeid = $time['time'];
						}
					}
				}
				if ($hasGoods) {
					$validtimes[] = $time;
				}
			}
		}
		if(!$timeid){
			return array('validtimes' =>$validtimes,'time' => array(), 'goods' => array(),'roomid'=>$roomid,'taskid'=>$taskid,'timeid'=>$timeid);
		}
		if($getnow){
			$goods = pdo_getall('jy_seckill_task_goods',array('taskid'=>$taskid,'timeid'=>$timeid));
		}else{
			$goods = pdo_getall('jy_seckill_task_goods',array('roomid'=>$roomid,'taskid'=>$taskid,'timeid'=>$timeid));
		}
		foreach ($goods as &$g) {
			$info=pdo_get('jy_weishop_goods',array('id'=>$g['goodsid']));
			$g['title']=$info['title'];
			$g['marketprice']=$info['originalprice'];
			$g['oldprice']=$info['price'];
			$g['image']=$info['image'];
			$seckillinfo = $this->getSeckill($g['goodsid'], 0, false);
			if ($g['hasoption']) {
				$total = 0;
				$count = 0;
				$options = pdo_fetchall('select tg.id,tg.goodsid,tg.optionid,tg.price,g.title,g.marketprice,tg.commission1,tg.commission2,tg.commission3,tg.total from ' . tablename('jy_seckill_task_goods') . '  tg  left join ' . tablename('jy_weishop_goods') . ' g on tg.goodsid = g.id  where tg.timeid=:timeid and tg.taskid=:taskid and tg.timeid=:timeid  and tg.goodsid=:goodsid and  tg.uniacid =:uniacid ', array(':timeid' => $time['id'], ':taskid' => $taskid, ':goodsid' => $g['goodsid'], ':uniacid' => $_SESSION['uniacid']));
				$price = $options[0]['price'];
				$marketprice = $options[0]['marketprice'];

				foreach ($options as $option) {
					$total += $option['total'];

					if ($option['price'] < $price) {
						$price = $option['price'];
					}

					if ($marketprice < $option['marketprice']) {
						$marketprice = $option['marketprice'];
					}
				}

				$g['price'] = $price;
				$g['marketprice'] = $marketprice;
				$g['total'] = $total;
				$g['count'] = $seckillinfo['count'];
				$g['percent'] = 100 < $seckillinfo['percent'] ? 100 : $seckillinfo['percent'];
			}else {
				$g['count'] = $seckillinfo['count'];
				$g['percent'] = 100 < $seckillinfo['percent'] ? 100 : $seckillinfo['percent'];
			}
			$g['marketprice'] =$g['marketprice'];
			$g['price'] =$g['price'];
		}
		unset($g);
		$goods=$goods?:array();
		return array('validtimes'=>$validtimes,'time' => $time,'goods' => $goods,'roomid'=>$roomid,'taskid'=>$taskid,'timeid'=>$timeid);
	}
	public function get_prefix()
	{
		global $_AR;
		return 'jy_seckill_' .  '_' . $_SESSION['uniacid'] . '_' . '_seckill_';
	}

	public function setTaskCache($id)
	{
		global $_AR;
		$redis_prefix =  $this->get_prefix();
		$task = pdo_get('jy_seckill_task',array('id'=>$id));
		$this->redis()->delete($redis_prefix . 'info_' . $id);
		$this->redis()->hMset($redis_prefix . 'info_' . $id, $task);
		$allrooms = pdo_getall('jy_seckill_task_room',array('enabled'=>1,'taskid'=>$id,'uniacid'=>$_SESSION['uniacid']));
		$this->redis()->delete($redis_prefix . 'rooms_' . $id);
		foreach ($allrooms as $room) {
			$this->redis()->rPush($redis_prefix . 'rooms_' . $id, ijson_encode($room));
		}
		$this->redis()->delete($redis_prefix . 'times_' . $id);
		$alltimes = pdo_getall('jy_seckill_task_time',array('taskid'=>$id,'uniacid'=>$_SESSION['uniacid']));
		$redisgoods = array();
		foreach ($alltimes as &$time) {
			$goods = pdo_getall('jy_seckill_task_goods',array('taskid'=>$id,'timeid'=>$time['time'],'uniacid'=>$_SESSION['uniacid']));
			if (!empty($goods)) {
				if (!isset($redisgoods[$time['time']]) || !is_array($redisgoods[$time['time']])) {
					$redisgoods['time-' . $time['time']] = array();
				}
				$this->redis()->rPush($redis_prefix . 'times_' . $id, ijson_encode($time));
				$redisgoods['time-' . $time['time']] = ijson_encode($goods);
			}
		}
		$this->redis()->delete($redis_prefix . 'goods_' . $id);
		if (!empty($redisgoods)) {
			$this->redis()->hMset($redis_prefix . 'goods_' . $id, $redisgoods);
		}
	}

	/**
     * 获取任务
     * @param $taskid
     * @return bool|int|string
     */
	public function usedDate($taskid)
	{
		if (is_error(redis())) {
			return false;
		}

		global $_AR;
		$redis_prefix =  $this->get_prefix();
		$calendar = redis()->hGetAll($redis_prefix . 'calendar');
		if (!is_array($calendar) || empty($calendar)) {
			return false;
		}

		foreach ($calendar as $k => $v) {
			if (!empty($v) && is_array($v)) {
				if ($v['taskid'] == $taskid) {
					return $k;
				}
			}
		}

		return false;
	}

	/**
     * 获取今天的秒杀任务
     * @return mixed
     */
	public function getTodaySeckill()
	{
		$redis_prefix =  $this->get_prefix();
		global $_AR;
		$year = date('Y');
		$month = date('m');		
		return $this->redis()->hGet($redis_prefix . 'calendar_' . $year . '_' . $month, date('Y-m-d'));
	}

	public function getTodaySeckillInfo()
	{
		if (is_error($this->redis())) {
			return false;
		}

		global $_AR;
		$taskid =  $this->getTodaySeckill();

		if (!empty($taskid)) {
			return  $this->getTaskInfo($taskid);
		}

		return false;
	}

	public function getRooms($taskid)
	{
		global $_AR;
		global $_RQ;
		$redis = $this->redis();
		if (is_error($this->redis())) {
			return false;
		}
		$redis_prefix =  $this->get_prefix();
		$allrooms = array();
		$rooms = $redis->lGetRange($redis_prefix . 'rooms_' . $taskid, 0, -1);
		foreach ($rooms as $room) {
			$room = json_decode($room, true);
			if (is_array($room)) {
				$allrooms[] = $room;
			}
		}
		return $allrooms;
	}

	public function getMainRoom($taskid)
	{
		if (is_error($this->redis())) {
			return false;
		}

		global $_AR;
		global $_RQ;
		$redis = $this->redis();
		$rooms =  $this->getRooms($taskid);

		if (empty($rooms)) {
			return false;
		}

		return $rooms[0];
	}

	public function getRoomInfo($taskid, $roomid)
	{
		global $_AR;

		if (is_error($this->redis())) {
			return false;
		}

		$rooms =  $this->getRooms($taskid);

		foreach ($rooms as $room) {
			if ($room['id'] == $roomid) {
				return $room;
			}
		}

		return false;
	}

	public function getTaskInfo($taskid)
	{
		global $_AR;
		global $_RQ;

		if (is_error($this->redis())) {
			return false;
		}

		$redis = $this->redis();
		$redis_prefix =  $this->get_prefix();
		$info = $redis->hGetAll($redis_prefix . 'info_' . $taskid);

		if (empty($info)) {
			return false;
		}

		return $info;
	}

	public function getTaskTimes($taskid)
	{
		global $_AR;
		global $_RQ;
		$redis = $this->redis();
		if (is_error($this->redis())) {
			return false;
		}
		$redis_prefix =  $this->get_prefix();
		$times = $redis->lGetRange($redis_prefix . 'times_' . $taskid, 0, -1);
		$alltimes = array();
		if (empty($times)) {
			return false;
		}
		foreach ($times as $time) {
			$time = json_decode($time, true);
			if (is_array($time)) {
				$alltimes[] = $time;
			}
		}
		return $alltimes;
	}

	public function getTaskGoods($taskid)
	{
		global $_AR;
		global $_RQ;
		$redis = $this->redis();

		if (is_error($this->redis())) {
			return false;
		}

		$redis_prefix =  $this->get_prefix();
		$info = $redis->hGetAll($redis_prefix . 'goods_' . $taskid);

		if (empty($info)) {
			return false;
		}

		return $info;
	}

	public function deleteTodaySeckill()
	{
		global $_AR;

		if (is_error($this->redis())) {
			return false;
		}

		$redis_prefix =  $this->get_prefix();
		$year = date('Y');
		$month = date('m');
		$date = date('Y-m-d');
		$this->redis()->hDel($redis_prefix . 'calendar_' . $year . '_' . $month, $date);
	}

	public function getSeckillCount($taskid, $timeid, $goodsid, $optionid = 0, $mid = '')
	{
		global $_AR;
		global $_RQ;
		$optionid = (int) $optionid;

		if (is_error($this->redis())) {
			return false;
		}

		$redis = $this->redis();
		$date = date('Y-m-d');
		$redis_prefix =  $this->get_prefix();
		$keys = $redis->keys($redis_prefix . 'queue_' . $date . '_' . $taskid . '_' . $timeid . '_' . $goodsid . '_*');

		if (empty($keys)) {
			return array('count' => 0, 'notpay' => 0, 'selfcount' => 0, 'selfnotpay' => 0, 'selftotalcount' => 0, 'selftotalnotpay' => 0);
		}

		$count = 0;
		$notpay = 0;
		$selfcount = 0;
		$selftotalcount = 0;
		$selfnotpay = 0;
		$selftotalnotpay = 0;

		foreach ($keys as $key) {
			$arr = explode('_', $key);
			$key_optionid = (int) $arr[11];
			$queue = $redis->lGetRange($key, 0, -1);
			foreach ($queue as $data) {
				$data = @json_decode($data, true);

				if (!is_array($data)) {
					continue;
				}

				if ((0 < $optionid) && ($key_optionid === $optionid)) {
					++$count;
				}
				else {
					if ($optionid == 0) {
						++$count;
					}
				}

				if ($data['status'] <= 0) {
					++$notpay;
				}

				if (!empty($mid) && ($data['mid'] == $mid)) {
					if ($key_optionid == $optionid) {
						++$selfcount;
					}

					++$selftotalcount;
				}

				if (($data['status'] <= 0) && !empty($mid) && ($data['mid'] == $mid)) {
					if ($key_optionid === $optionid) {
						++$selfnotpay;
					}

					++$selftotalnotpay;
				}
			}
		}
		return array('count' => $count, 'notpay' => $notpay, 'selfcount' => $selfcount, 'selfnotpay' => $selfnotpay, 'selftotalcount' => $selftotalcount, 'selftotalnotpay' => $selftotalnotpay);
	}

	public function getSeckillGoods($taskid, $time, $goodsid)
	{
		global $_AR;
		global $_RQ;
		if (is_error($this->redis())) {
			return false;
		}

		$redis_prefix =  $this->get_prefix();
		$timegoods = array();
		$goods = $this->redis()->hGetAll($redis_prefix . 'goods_' . $taskid);

		if (empty($goods)) {
			return false;
		}

		$goods = @json_decode($goods['time-' . $time], true);

		if (!is_array($goods)) {
			return false;
		}
		foreach ($goods as $g) {
			if (!is_array($g)) {
				return false;
			}
			if (($g['goodsid'] == $goodsid) || ($goodsid == 'all')) {
				$timegoods[] = $g;
			}
		}

		return $timegoods;
	}

	/**
     * 设置秒杀数据
     */
	public function setSeckill($seckillinfo, $goods, $mid, $orderid, $status, $createtime='')
	{
		global $_AR;
		global $_RQ;
		if (is_error($this->redis())) {
			return false;
		}
		$createtime=$createtime?:time();
		$taskid = $seckillinfo['taskid'];
		$timeid = $seckillinfo['timeid'];
		$goodsid = $goods['goodsid'];
		$optionid = intval($goods['optionid']);
		$date = date('Y-m-d');
		$redis_prefix =  $this->get_prefix();
		$key = $redis_prefix . 'queue_' . $date . '_' . $taskid . '_' . $timeid . '_' . $goodsid . '_' . $optionid;
		$redis = $this->redis();
		if ($redis->ttl($key) == -1) {
			$redis->expireAt($key, $seckillinfo['endtime'] + 1);
		}
		$index = -1;
		$queue = $redis->lGetRange($key, 0, -1);

		foreach ($queue as $dindex => $data) {
			$data = @json_decode($data, true);

			if (!is_array($data)) {
				continue;
			}

			if (($data['orderid'] == $orderid) && ($data['mid'] == $mid)) {
				$index = $dindex;
				break;
			}
		}
		$data = array('orderid' => $orderid, 'mid' => $mid, 'status' => $status, 'createtime' => $createtime);
		if ($index == -1) {
			$i = 1;
			while ($i <= $goods['total']) {
				$push = $redis->lPush($key, json_encode($data));
				++$i;
			}
		}else {
			$push = $redis->lSet($key, $index, json_encode($data));
		}
		return $key;
	}
	/**
     * 删除未付款过期数据
     */
	public function deleteSeckill()
	{
		global $_AR;

		if (is_error($this->redis(true))) {
			return false;
		}

		$currenttime = time();
		$redis = $this->redis();
		$redis_prefix =  $this->get_prefix();
		$keys = $redis->keys($redis_prefix . 'queue_*');
		$orders = array();

		foreach ($keys as $key) {
			$queue = $redis->lGetRange($key, 0, -1);
			$tags = explode('_', $key);
			$taskid = $tags[8];
			$task =  $this->getTaskInfo($taskid);
			$closesec = $task['closesec'];

			if (!empty($queue)) {
				foreach ($queue as $value) {
					$data = @json_decode($value, true);

					if (!is_array($data)) {
						continue;
					}

					if (($data['status'] <= 0) && ($closesec <= $currenttime - $data['createtime'])) {
						$redis->lRemove($key, $value, 1);

						if (!in_array($data['orderid'], $orders)) {
							$orders[] = $data['orderid'];
						}
					}
				}
			}

			if ($redis->lLen($key) <= 0) {
				$redis->delete($key);
			}

			if (!empty($orders)) {
				//$p = com('coupon');
				foreach ($orders as $orderid) {
					$o =pdo_get('jy_weishop_order',array('id'=>$orderid));
					if (!empty($o) && ($o['status'] == 0)) {
						if ($o['isparent'] == 0) {
							if ($p) {
								if (!empty($o['couponid'])) {
									//$p->returnConsumeCoupon($o['id']);
								}
							}

							//m('order')->setStocksAndCredits($o['id'], 2);
							//m('order')->setDeductCredit2($o);

							if (0 < $o['deductprice']) {
								//m('member')->setCredit($o['mid'], 'credit1', $o['deductcredit'], array('0', $_AR['shopset']['shop']['name'] . '秒杀自动关闭订单返还抵扣积分 积分: ' . $o['deductcredit'] . ' 抵扣金额: ' . $o['deductprice'] . ' 订单号: ' . $o['ordersn']));
							}
						}

						pdo_update('jy_weishop_order',array('status'=>-1,'createtime'=>time()),array('id'=>$orderid));
					}
				}
			}
		}

		return true;
	}

	public function getSeckill($goodsid, $optionid = 0, $realprice = true, $mid = '',$isnoexi=false)
	{
		global $_AR;
		$redis = $this->redis($isnoexi);
		if (is_error($redis)){
			return false;
		}
		static $deletedSeckill;
		if (is_null($deletedSeckill)) {
			 $this->deleteSeckill();
			$deletedSeckill = true;
		}
		$id =  $this->getTodaySeckill();
		if (empty($id)) {
			return false;
		}
		$times =  $this->getTaskTimes($id);
		$options = array();
		$currenttime = time();
		$timegoods = array();
		$sktime = 0;
		$timeid = 0;
		$roomid = 0;
		$taskid = 0;
		$goods_starttime = 0;
		$goods_endtime = 0;
		$setting=$this->plugin_setting('basic');
		foreach ($times as $key => $time) {
			$starttime = strtotime(date('Y-m-d ' . $time['time'] . ':00:00'));
			if (isset($times[$key + 1])) {
				$end = $times[$key + 1]['time'] - 1;
				$endtime = strtotime(date('Y-m-d ' . $end . ':59:59'));
			}else {
				$endtime = strtotime(date('Y-m-d 23:59:59'));
			}			
			if($setting['maxhours']>=1){
				$settime=$setting['maxhours']*3600+$starttime;
				$endtime=$settime<$endtime?$settime:$endtime;
			}
			$time['endtime'] = $endtime;
			$goods_endtime = $endtime;
			$time['starttime'] = $starttime;
			if (($starttime <= $currenttime) && ($currenttime <= $endtime)) {
				$timeid = $time['id'];
				$taskid = $time['taskid'];
				$goods_starttime = $starttime;
				$sktime = $time['time'];
				$timegoods =  $this->getSeckillGoods($id, $time['time'], $goodsid);
			}else {
				if ($currenttime < $starttime) {
					if (empty($timegoods)) {
						$timeid = $time['id'];
						$goods_starttime = $starttime;
						$taskid = $time['taskid'];
						$sktime = $time['time'];
						$timegoods =  $this->getSeckillGoods($id, $time['time'], $goodsid);
					}
				}
			}
		}
		$total = 0;
		$count = 0;
		$selfcount = 0;
		$selftotalcount = 0;
		$maxbuy = 0;
		$notpay = 0;
		$selfnotpay = 0;
		$selftotalnotpay = 0;
		$totalmaxbuy = 0;
		if (!empty($timegoods)) {
			$opswi = false;
			if (!empty($optionid)) {
				foreach ($timegoods as $tk => $tv) {
					$optionsset=json_decode($tv['optionsset'],true);
					if ($optionsset[$optionid]){
						$opswi = true;
					}
				}

				if (!$opswi) {
					return false;
				}
			}
			$roomid = $timegoods[0]['roomid'];
			$total = $timegoods[0]['total'];
			$price = $timegoods[0]['price'];
			$totalmaxbuy = $timegoods[0]['totalmaxbuy'];
			$optionsset=json_decode($timegoods[0]['optionsset'],true);
			if ((count($timegoods) <= 1) && empty($optionsset[$optionid])){
				$counts =  $this->getSeckillCount($id, $timeid, $timegoods[0]['goodsid'], 0, $mid);
				$count = $counts['count'];
				$selfcount = $counts['selfcount'];
				$selftotalcount = $counts['selftotalcount'];
				$notpay = $counts['notpay'];
				$selfnotpay = $counts['selfnotpay'];
				$selftotalnotpay = $counts['selftotalnotpay'];
				$maxbuy = $timegoods[0]['maxbuy'];
				$percent = ceil(($count / (empty($total) ? 1 : $total)) * 100);
				$options[] = $timegoods[0];
			}else {
				$total = 0;
				$price = $timegoods[0]['price'];
				$option_goods = NULL;
				if (!empty($optionid)) {
					foreach ($timegoods as $g) {
						$optionsset=json_decode($g['optionsset'],true);
						if ($optionsset[$optionid]){
							$total = $g['total'];
							$price = $optionprice = $optionsset[$optionid]['price'];
							$counts =  $this->getSeckillCount($id, $timeid, $g['goodsid'], $optionid, $mid);
							$count = $counts['count'];
							$selfcount = $counts['selfcount'];
							$selftotalcount = $counts['selftotalcount'];
							$selfnotpay = $counts['selfnotpay'];
							$selftotalnotpay = $counts['selftotalnotpay'];
							$notpay = $counts['notpay'];
							$maxbuy = $g['maxbuy'];
							$percent = ceil(($count / (empty($g['total']) ? 1 : $g['total'])) * 100);
							break;
						}
					}
				}else {
					foreach ($timegoods as $g) {
						$total += $g['total'];

						if ($g['price'] <= $price) {
							$price = $g['price'];
						}

						$options[] = $g;
					}

					$counts =  $this->getSeckillCount($id, $timeid, $g['goodsid'], 0, $mid);
					$count = $counts['count'];
					$selfcount = $counts['selfcount'];
					$selfnotpay = $counts['selfnotpay'];
					$notpay = $counts['notpay'];
					$selftotalcount = $counts['selftotalcount'];
					$selftotalnotpay = $counts['selftotalnotpay'];
					$percent = ceil(($count / (empty($total) ? 1 : $total)) * 100);
				}
			}

			if (!$realprice) {
				$price = $price;
			}

			$tag = '';
			$taskinfo =  $this->getTaskInfo($taskid);
			$roominfo =  $this->getRoomInfo($taskid, $roomid);

			if (!empty($taskinfo['tag'])) {
				$tag = $taskinfo['tag'];
			}

			if (!empty($roominfo['tag'])) {
				$tag = $roominfo['tag'];
			}

			$status = false;
			if (($goods_starttime <= $currenttime) && ($currenttime <= $goods_endtime)) {
				$status = 1;
			}
			else if ($currenttime < $goods_starttime) {
				$status = 0;
			}
			else {
				if ($goods_endtime < $currenttime) {
					$status = -1;
				}
			}

			return array('taskid' => $taskid, 'roomid' => $roomid, 'timeid' => $timeid, 'total' => $total, 'count' => $count, 'selfcount' => $selfcount, 'selftotalcount' => $selftotalcount, 'notpay' => $notpay, 'selfnotpay' => $selfnotpay, 'selftotalnotpay' => $selftotalnotpay, 'maxbuy' => $maxbuy, 'totalmaxbuy' => $totalmaxbuy, 'tag' => $tag, 'time' => $sktime, 'options' => $options, 'starttime' => $goods_starttime, 'endtime' => $goods_endtime, 'price' => $price,'optionprice' => $optionprice, 'percent' => $percent, 'status' => $status);
		}

		return false;
	}
	public function orderRefund($item)
	{
		$shopset = plugin('jy_weishop')->plugin_setting('shopset');
		$this->model('order/refund')->check_order_rerefund($item['id']);
		$ram=$shopset['name'] . '秒杀退款: ' . $realprice . '元 订单号: ' . $item['ordersn'];
		$this->model('order/refund')->refund_create($item);
	}

	public function setOrderPay($orderid)
	{
		if (is_error($this->redis(true))) {
			return false;
		}
		$redis = $this->redis(true);
		$redis_prefix =  $this->get_prefix();
		$date = date('Y-m-d');
		$order = pdo_get('jy_weishop_order',array('id'=>$orderid,'uniacid'=>$_SESSION['uniacid']));
		if (empty($order)) {
			return '';
		}
		if (intval($order['status']) < 0) {
			 $this->orderRefund($order);
			return 'refund';
		}
		$goods = pdo_getall('jy_weishop_order_goods',array('orderid'=>$order['id'],'isseckill'=>1,'uniacid'=>$_SESSION['uniacid']));
		foreach ($goods as $g) {
			$key = $redis_prefix . 'queue_' . $date . '_' . $g['seckill_taskid'] . '_' . $g['seckill_timeid'] . '_' . $g['goodsid'] . '_' . $g['optionid'];
			$queue = $redis->lGetRange($key, 0, -1);
			$paydata = json_encode(array('orderid' => $order['id'], 'mid' => $order['mid'], 'status' => 1, 'createtime' => $order['createtime']));

			if (empty($queue)) {
				 $this->orderRefund($order);
				return 'refund';
			}
			$has = false;
			foreach ($queue as $index => $value) {
				$data = @json_decode($value, true);
				if (!is_array($data)) {
					continue;
				}

				if (($data['orderid'] == $order['id']) && ($data['mid'] == $order['mid'])) {
					$has = true;
					$redis->lSet($key, $index, $paydata);
				}
			}
			if (!$has) {
				 $this->orderRefund($order);
				return 'refund';
			}
		}
		return '';
	}
	public function getTaskSeckillInfo()
	{
		global $_AR;
		if (is_error($this->redis())) {
			return false;
		}

		if (empty($taskid)) {
			$taskid =  $this->getTodaySeckill();

			if (empty($taskid)) {
				return false;
			}
		}
		$task =  $this->getTodaySeckillInfo();
		if (empty($taskid)) {
			return false;
		}
		$redis = $this->redis();
		$times =  $this->getTaskTimes($taskid);
		$options = array();
		$currenttime = time();
		$timegoods = array();
		$goods_starttime = 0;
		$goods_endtime = 0;
		$hasCurrent = false;
		$timegoods = false;
		$status = -1;

		foreach ($times as $key => $time) {
			$starttime = strtotime(date('Y-m-d ' . $time['time'] . ':00:00'));

			if (isset($times[$key + 1])) {
				$end = $times[$key + 1]['time'] - 1;
				$endtime = strtotime(date('Y-m-d ' . $end . ':59:59'));
			}
			else {
				$endtime = strtotime(date('Y-m-d 23:59:59'));
			}

			$time['endtime'] = $endtime;
			$time['starttime'] = $starttime;
			if (($starttime <= $currenttime) && ($currenttime <= $endtime)) {
				$timeid = $time['id'];
				$taskid = $time['taskid'];
				$goods_starttime = $starttime;
				$goods_endtime = $endtime;
				$sktime = $time['time'];
				$timegoods =  $this->getSeckillGoods($taskid, $time['time'], 'all');
				$hasCurrent = true;
				$status = 0;
				break;
			}

			if ($currenttime < $starttime) {
				$timeid = $time['id'];
				$taskid = $time['taskid'];
				$goods_starttime = $starttime;
				$goods_endtime = $endtime;
				$sktime = $time['time'];
				$timegoods =  $this->getSeckillGoods($taskid, $time['time'], 'all');
				$hasCurrent = true;
				$status = 1;
				break;
			}
		}

		if (empty($timegoods)) {
			return false;
		}

		shuffle($timegoods);
		$allgoods = array();

		foreach ($timegoods as $g) {
			if (10 <= count($allgoods)) {
				break;
			}

			if (!in_array($g['goodsid'], $allgoods)) {
				$allgoods[$g['goodsid']][] = array('optionid' => $g['optionid'], 'price' => $g['price']);
			}
		}

		$goodsids = array_keys($allgoods);
		$dbgoods = pdo_getall('jy_weishop_goods',array('id'=>$goodsids,'uniacid'=>$_SESSION['uniacid']),array('id','image','marketprice'));
		$goods = array();
		foreach ($allgoods as $gid => $tgs) {
			$price = $tgs[0]['price'];
			foreach ($tgs as $tg) {
				if ($tg['price'] < $price) {
					$price = $tg['price'];
				}
			}
			$goods[] = array('thumb' => tomedia($dbgoods[$gid]['image']), 'price' => $price, 'marketprice' => $dbgoods[$gid]['marketprice']);
		}
		return array('tag' => $task['tag'], 'status' => $status, 'time' => $sktime < 10 ? '0' . $sktime : $sktime, 'endtime' => $goods_endtime, 'starttime' => $goods_starttime, 'goods' => $goods);
	}
	public function checkBuy($seckillinfo, $title='', $unit = '',$num=1)
	{
		if (empty($unit)) {
			$unit = '件';
		}
		if (empty($seckillinfo['starttime'])) {
			return false;
		}
		if($seckillinfo['starttime']>time()){
			exi( $title . ' 秒杀还没开始 !','error');
		}
		if($seckillinfo['endtime'] && $seckillinfo['endtime']<time()){
			exi( $title . ' 秒杀已结束，下次再来吧 !','error');
		}
		if (100 <= $seckillinfo['percent']) {
			if (0 < $seckillinfo['notpay']) {
				exi( $title . '已经抢完了 ，但还有 ' . $seckillinfo['notpay'] . ' ' . $unit . '未付款的, 抓住机会哦~','error');
			}

			exi( $title . ' 已经抢完了 !','error');
		}

		if (0 < $seckillinfo['totalmaxbuy']) {
			if ($seckillinfo['totalmaxbuy'] <= $seckillinfo['selftotalcount']) {
				if (0 < $seckillinfo['selftotalnotpay']) {
					exi( $title . '最多抢购 ' . $seckillinfo['totalmaxbuy'] . ' ' . $unit . ',  您有' . $seckillinfo['selftotalnotpay'] . '个未付款的，抓紧付款哦~','error');
				}

				exi( $title . '您已经抢购 ' . $seckillinfo['totalmaxbuy'] . ' ' . $unit . '了哦，不能继续抢购了，看看别的吧!','error');
			}
		}

		if (0 < $seckillinfo['maxbuy']) {
			if ($seckillinfo['maxbuy'] <= $seckillinfo['selfcount']) {
				if (0 < $seckillinfo['selfnotpay']) {
					exi( $title . ' 最多抢购 ' . $seckillinfo['maxbuy'] . ' ' . $unit . ',  您有' . $seckillinfo['selfnotpay'] . '个未付款的，抓紧付款哦~','error');
				}
				exi($title . '您已经抢购 ' . $seckillinfo['maxbuy'] . ' ' . $unit . '了哦，不能继续抢购了，看看别的吧!','error');
			}
			if ($seckillinfo['maxbuy'] < $num + $seckillinfo['selfcount']) {
				if (0 < $seckillinfo['selfnotpay']) {
					exi( $title . ' 最多抢购 ' . $seckillinfo['maxbuy'] . ' ' . $unit . ',  您有' . $seckillinfo['selfnotpay'] . '个未付款的，抓紧付款哦~','error');
				}
				$last=$seckillinfo['maxbuy']-$seckillinfo['selfcount'];
				if($seckillinfo['selfcount']){
					exi($title . '您已经抢购 ' . $seckillinfo['selfcount'] . ' ' . $unit . '了哦!还可购买'.$last. ' ' . $unit ,'error');
				}else{
					exi($title . '您只可以购买'.$last. ' ' . $unit ,'error');
				}
			}
		}
		return true;
	}
	public function checkTaskGoods($taskid, $roomid, $goodsids)
	{
		if (is_error($this->redis())) {
			return false;
		}

		if (empty($goodsids)) {
			return true;
		}

		$error = array();
		$times =  $this->getTaskTimes($taskid);

		if (!is_array($times)) {
			return true;
		}

		foreach ($times as $time) {
			$goods =  $this->getSeckillGoods($taskid, $time['time'], 'all');

			if (!is_array($goods)) {
				continue;
			}

			foreach ($goods as $g) {
				if (in_array($g['goodsid'], $goodsids) && ($g['roomid'] != $roomid)) {
					$room =  $this->getRoomInfo($taskid, $g['roomid']);
					$goodstitle = pdo_getcolumn('jy_weishop_goods',array('id'=>$g['goodsid']),'title');
					if (!isset($error['goods-' . $g['goodsid']])) {
						$error['goods-' . $g['goodsid']] = '商品&lt;span class=\'text text-danger\'&gt;【' . $goodstitle . '】&lt;/span&gt;在会场&lt;a href=\'' . $url . '\' target=\'_blank\'&gt;【' . $room['title'] . '】&lt;/a&gt;中的 &lt;span class=\'text text-danger\'&gt;' . $time['time'] . '&lt;/span&gt; 点场已经存在，不能重复添加';
					}
				}
			}
		}

		if (!empty($error)) {
			exi(implode('<br/>', $error),'error');
		}

		return true;
	}
	public function getcalendar($month='',$year='')
	{
		$day = date("t",strtotime($year.'-'.$month));
		//$day = cal_days_in_month(CAL_GREGORIAN, $month,);
		return $day;
	}
}
?>